/**
+ * @Project: Runer
 * @Title: ActivityRegister.java
 * @Package com.runlooker.runer.registerAndLogin
 * @author town
 * @date 2014-4-16 下午8:25:07
 * @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
 * @version V1.0
 */
package com.runlooker.runer.ui.rigister;

import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.XMPPException;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseActivity;
import com.runlooker.runer.util.NetworkUtil;
import com.runlooker.runer.util.T;

/**
 * @ClassName ActivityRegister
 * @Description 模块描述
 * @author town
 * @Date 2014-4-16
 */
public class RegisterActivity extends BaseActivity {

	public final static String NAME_KEY = "name";
	public final static String EMAIL_KEY = "email";
	private final String tag = RegisterActivity.class.getSimpleName();
	private EditText mUserNameET;
	private EditText mUserAccountET;
	private EditText mPasswordET;
	private EditText emailET;
	private Button registerBT;

	private String mUserName;
	private String mUserAcount;
	private String mPassword;
	private String mEmail;
	private XmppService mXmppService;
	private Thread mThread;

	private final Map<String, String> mAttributes = new HashMap<String, String>();

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MyApplication.SUCCESS:// 注册成功
				finish();
				break;
			case MyApplication.EXCEPTION:// 注册失败
				T.showShort(RegisterActivity.this, msg.obj.toString());
				break;
			default:
				break;
			}
		}

	};

	ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppService = ((XmppService.XMPPBinder) service).getService();
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mXmppService = null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		initialize();
		registEvent();
	}

	private void initialize() {
		Intent intent = new Intent(RegisterActivity.this, XmppService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		mUserAccountET = (EditText) findViewById(R.id.et_resiter_useracount);
		mPasswordET = (EditText) findViewById(R.id.et_resiter_passwd1);
		emailET = (EditText) findViewById(R.id.et_resiter_email);
		mUserNameET = (EditText) findViewById(R.id.et_resiter_username);
		registerBT = (Button) findViewById(R.id.btn_resiter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
		handler.removeCallbacksAndMessages(null);
	}

	/**
	 * 根据指定设置创建一个帐号,成功创建帐号会将本地手机信息， 以及用户昵称等信息上传到服务器
	 * 
	 * 
	 * @param username
	 *            the username of the account.
	 * @param password
	 *            the password of the account.
	 * @return true if the account was created successfully.
	 * @throws XMPPException
	 */
	private void createAccount(final String account, final String password,
			final Map<String, String> mAttributes) throws Exception {
		if (mXmppService != null) {
			mXmppService.register(account, password, mAttributes);
		} else {
			throw new XMPPException("mXmppService未初始化！");
		}
	}

	/**
	 * 注册各种事件
	 * 
	 * 
	 * @Title: registEvent
	 * @Description: 方法描述
	 */
	private void registEvent() {
		// 点击注册
		registerBT.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUserName = mUserNameET.getText().toString().trim();
				mUserAcount = mUserAccountET.getText().toString().trim();
				mPassword = mPasswordET.getText().toString().trim();
				mEmail = emailET.getText().toString().trim();
				mAttributes.put(NAME_KEY, mUserName);
				mAttributes.put(EMAIL_KEY, mEmail);
				if (checkUserName() && checkAccount() && checkPassword()
						&& checkEmail()) {
					if (NetworkUtil.getNetworkState(RegisterActivity.this) == NetworkUtil.NETWORN_NONE) {
						T.showShort(RegisterActivity.this, "无法连接网络！");
					} else {
						if (mThread == null) {
							mThread = new Thread(new Runnable() {
								@Override
								public void run() {
									try {
										createAccount(mUserAcount, mPassword,
												mAttributes);
										handler.sendEmptyMessage(MyApplication.SUCCESS);
									} catch (Exception e) {
										Message msg = Message.obtain();
										msg.obj = e;
										msg.what = MyApplication.EXCEPTION;
										handler.sendMessage(msg);
										e.printStackTrace();
									}
									if (mThread != null)
										synchronized (mThread) {
											mThread = null;
										}
								}
							});
							mThread.start();
						}
					}
				}
			}
		});
	}

	public void back(View view) {
		finish();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	private boolean checkAccount() {
		if (mUserAcount.length() > 0) {
			return true;
		} else {
			T.showShort(RegisterActivity.this, "帐号不能为空！");
			return false;

		}
	}

	private boolean checkPassword() {
		if (mPassword.length() > 0) {
			return true;
		} else {
			T.showShort(RegisterActivity.this, "密码不能为空！");
			return false;
		}
	}

	private boolean checkUserName() {
		if (mUserName.length() > 0) {
			return true;
		} else {
			T.showShort(RegisterActivity.this, "用户昵称不能为空！");
			return false;
		}
	}

	/**
	 * 检查邮件格式
	 * 
	 * @return true if the email is valid.
	 */
	private boolean checkEmail() {
		if (mEmail.contains("@")) {
			return true;
		} else {
			T.showShort(RegisterActivity.this, "邮件格式不对！");
			return false;
		}
	}

}
